function tocObject() {
    let tocObj = [];
    let accWb = wps.Application.ActiveWorkbook.Name;
    let accWS = wps.Application.ActiveSheet.Name;
    for (let i = 1; i <= wps.Application.Workbooks.Count; i++) {
        let itemWb = wps.Application.Workbooks.Item(i)
        let itemObj = {
            wbName: itemWb.Name,
            index: i,
            isActivate: itemWb.Name == accWb,
            sheets: (() => {
                // 非激活工作簿则提前结束
                if (!(itemWb.Name == accWb)) {
                    return [];
                }
                let s = [];
                for (let z = 1; z <= itemWb.Worksheets.Count; z++) {
                    let ztem = itemWb.Worksheets.Item(z);
                    s.push({
                        parent: itemWb.Name,
                        index: z,
                        shName: ztem.Name,
                        visible: ztem.Visible === 0 ? false : true,
                        isAccWorkSheet: itemWb.Name == accWb && accWS == ztem.Name,
                    })
                }
                return s;
            })()
        }
        tocObj.push(itemObj)
    }
    return tocObj;
}

function tocHtmlAll() {

    $('#tocBox').empty()

    let objTree = tocObject()
    html = objTree.map(o =>
        `
<div class="tab" style="order:${o.isActivate ? 0 : o.index}" ${o.isActivate ? `id="AccWorkBook"` : ""}>
<input type="checkbox" id="wb${o.index}" ${wps.PluginStorage.getItem('listAllTocLi') ? `checked="true"` : o.isActivate ? `checked="true"` : ""}>
<label class="tab-label" for="wb${o.index}" onclick="appenToc('${o.wbName}','#tocItem${o.index}');">${o.wbName}</label>
<div class="tab-content" id="tocItem${o.index}">
${o.isActivate ? `<ol class="sheets" id="drag">${o.sheets.map(e => `<li class="acWbSheetItem" id="${e.shName}"> <a ${e.isAccWorkSheet ? `id="accWorksheet"` : ''} ${e.visible ? `onclick="wps.Application.Workbooks.Item('${o.wbName}').Activate();wps.Application.Sheets.Item('${e.shName}').Activate()"` : ""}>${e.shName}${!e.visible ? `<strong class="sheetUnvisible"></strong>` : ""}</a> </li>`).join('\n')}</ol>` : ``}
</div>
</div>
`
    );
    $('#tocBox').append(html);
}

function appenToc(wb, appendTo) {
    let foo = $(appendTo).text().length < 10;
    if (foo) {
        $(appendTo).empty()
        let sheets = wps.Application.Workbooks.Item(wb).Worksheets;
        let list = []
        for (let i = 1; i <= sheets.Count; i++) {
            let iSheName = sheets.Item(i).Name;
            let visible = sheets.Item(i).Visible === 0 ? false : true;
            list.push(`<li class="sheetItem"> <a class="sheetItemLink" ${visible ? `onclick="wps.Application.Workbooks.Item('${wb}').Activate();wps.Application.Sheets.Item('${iSheName}').Activate()"` : ""}>${iSheName}${!visible ? `<strong class="sheetUnvisible"></strong>` : ""}</a></li>`)
        }
        let listHtml = `<ol class="sheets">${list.join("")}</ol>`;
        $(appendTo).append(listHtml)
    }
}

function onlyAccWb() {
    let checkSta = wps.PluginStorage.getItem("toc_onlyActiveWorkbook");
    if (checkSta) {
        $('.tab:not(#AccWorkBook)').remove()
    }
}

document.onload = (() => {
    tocHtmlAll()
    onlyAccWb()
})();
wps.ApiEvent.AddApiEventListener('WorkbookOpen', () => {
    location.reload(true)
    onlyAccWb()
})
wps.ApiEvent.AddApiEventListener('WindowActivate', () => {
    location.reload(true)
    onlyAccWb()
})
wps.ApiEvent.AddApiEventListener('SheetActivate', () => {
    location.reload(true)
    onlyAccWb()
})

if(wps.PluginStorage.getItem("toc_onlyActiveWorkbook")){
    $('#onlyAccWb').attr("checked","true")
}

function summaryPosition() {
    let position = wps.GetTaskPane(1).DockPosition
    if (position !== 0) {
        wps.GetTaskPane(1).DockPosition = 0;
        document.getElementById("arrPosition").innerHTML = "&rarr;"
    } else {
        wps.GetTaskPane(1).DockPosition = 2;
        document.getElementById("arrPosition").innerHTML = "&larr;"
    }
}

$('#onlyAccWb').on('click', function () {
    let checkSta = $('#onlyAccWb').prop('checked')
    if (checkSta) {
        wps.PluginStorage.setItem("toc_onlyActiveWorkbook",true)
        $('.tab:not(#AccWorkBook)').remove()
    } else {
        wps.PluginStorage.setItem("toc_onlyActiveWorkbook",false)
        tocHtmlAll()
    }
});

// 拖动排序
$(function(){
    $("#drag").sortable();
    $(".acWbSheetItem").draggable({
        connectToSortable: "#drag"
    });
    $('.acWbSheetItem').on('dragstop', function () {
            let sh = $(this).attr('id');
            let after = $(this).next().attr('id');
            // 只需知道移到哪一个之前即可，否则移到最后；
            if(after){
                let afterSh = Application.Worksheets.Item(after)
                Application.Worksheets.Item(sh).Move(afterSh,undefined);
            }else{
                let lastSh = Application.Worksheets.Item(Application.Worksheets.Count);
                Application.Worksheets.Item(sh).Move(undefined,lastSh)
            }
            location.reload(true)
    });
    $("ul li").disableSelection();
})

